package io.renren.common.utils.PayUtils.WxPay.weixin;


import io.renren.common.utils.PayUtils.WxPay.weixin.client.TenpayHttpClient;
import io.renren.common.utils.PayUtils.WxPay.weixin.util.ConstantUtil;
import io.renren.common.utils.PayUtils.WxPay.weixin.util.MD5Util;
import io.renren.common.utils.PayUtils.WxPay.weixin.util.XMLUtil;
import org.jdom.JDOMException;
import org.json.JSONException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class PrepayIdRequestHandler extends RequestHandler {

	public PrepayIdRequestHandler(HttpServletRequest request,
			HttpServletResponse response) {
		super(request, response);
	}
	
	/**
	 * 创建签名MD5
	 * 
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws Exception
	 */
	public String createMD5Sign() throws UnsupportedEncodingException {
		StringBuffer sb = new StringBuffer();
		Set<?> es = super.getAllParameters().entrySet();
		Iterator<?> it = es.iterator();
		while (it.hasNext()) {
			@SuppressWarnings("rawtypes")
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			sb.append(k + "=" + v + "&");
		}
		String params = sb.substring(0, sb.lastIndexOf("&"));
		String stringSignTemp = params+"&key="+ ConstantUtil.WX_API_KEY;
//		String enc = TenpayUtil.getCharacterEncoding(this.request, this.response);
		String appsign = MD5Util.MD5Encode(stringSignTemp.toString(), "utf-8").toUpperCase();
		
		return appsign;
	} 

	// 提交预支付
	public String sendPrepay() throws JSONException, JDOMException, IOException {
		String prepayid = "";
		Set<?> es = super.getAllParameters().entrySet();
		Iterator<?> it = es.iterator();
		Map<String,Object> map = new TreeMap<String,Object>();
		while (it.hasNext()) {
			@SuppressWarnings("rawtypes")
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			if (null != v && !"".equals(v) && !"appkey".equals(k)) {
				map.put(k, v);
			}
		}
		//调用统一下单接口，参数拼接为xml格式
		String params = XMLUtil.createXml(map);
		String requestUrl = super.getGateUrl();
		this.setDebugInfo(this.getDebugInfo() + "\r\n" + "requestUrl:"
				+ requestUrl);
		TenpayHttpClient httpClient = new TenpayHttpClient();
		httpClient.setReqContent(requestUrl);
		String resContent = "";
		this.setDebugInfo(this.getDebugInfo() + "\r\n" + "post data:" + params);
		if (httpClient.callHttpPost(requestUrl, params)) {
			resContent = httpClient.getResContent();
			Map<String, String> map2 = XMLUtil.doXMLParse(resContent);
			prepayid = (String) map2.get("prepay_id");
			this.setDebugInfo(this.getDebugInfo() + "\r\n" + "resContent:"
					+ resContent);
		}
		return prepayid;
	}

}
